package com.lw.leetcode.str.a;

import java.util.Arrays;

/**
 * 821. 字符的最短距离
 *
 * @Author liw
 * @Date 2021/6/5 22:51
 * @Version 1.0
 */
public class ShortestToChar {

    public static void main(String[] args) {
        ShortestToChar test = new ShortestToChar();
        String s = "loveleetcode";
        // "loveleetcode"
        //"e"
        int[] ints = test.shortestToChar(s, 'e');
        System.out.println(Arrays.toString(ints));
    }

    public int[] shortestToChar(String s, char c) {
        int length = s.length();
        int[] arr = new int[length];
        int[] arr2 = new int[length];
        Arrays.fill(arr, -1);
        int j = 0;
        for (int i = 0; i < length; i++) {
            char value = s.charAt(i);
            if (c == value) {
                arr[i] = 0;
                arr2[j++] = i;
            }
        }
        int v = 1;
        for (int i = arr2[0] - 1; i >= 0; i--) {
            arr[i] = v++;
        }
        v = 1;
        for (int i = arr2[j - 1] + 1; i < length; i++) {
            arr[i] = v++;
        }
        int end = 1;
        int st = 0;
        for (int i = arr2[0] + 1; i < arr2[j - 1]; i++) {
            if (arr[i] == 0) {
                st++;
                end++;
                continue;
            }
            arr[i] = Math.min(i - arr2[st], arr2[end] - i);
        }
        return arr;
    }
}
